#include "smastrategy.h"




void SMAStrategy::setParameters(int shortPeriod, int longPeriod)
{
    m_shortPeriod = shortPeriod;
    m_longPeriod = longPeriod;
    m_prices.clear();
    m_lastShortSMA = 0.0;
    m_lastLongSMA = 0.0;
}



void SMAStrategy::onCandle(const CandleData &candle)
{
    //将收盘价存储到容器中
    m_prices.append(candle.close);

    m_lastPrice = candle.close;

    // 确保有足够的数据计算均线
    if (m_prices.size() < m_longPeriod) return;

    // 计算短期均线
    double shortSMA = std::accumulate(
                          m_prices.end() - m_shortPeriod,//减去短期周期  获得减去短期周期的迭代器
                          m_prices.end(), 0.0) / m_shortPeriod;

    // 计算长期均线
    double longSMA = std::accumulate(
                         m_prices.end() - m_longPeriod,
                         m_prices.end(), 0.0) / m_longPeriod;

    // 金叉: 短期均线上穿长期均线，买入
    if (shortSMA > longSMA && m_lastShortSMA <= m_lastLongSMA) {
        if (m_holdings == 0) {
            buy(candle, m_balance / candle.close * 0.95); // 用95%的资金买入
        }
    }
    // 死叉: 短期均线下穿长期均线，卖出
    else if (shortSMA < longSMA && m_lastShortSMA >= m_lastLongSMA) {
        if (m_holdings > 0) {
            sell(candle); // 卖出所有持仓
        }
    }

    m_lastShortSMA = shortSMA;
    m_lastLongSMA = longSMA;

    // 限制数据量，避免内存过度增长
    if (m_prices.size() > m_longPeriod * 2) {
        m_prices.removeFirst();
    }
}

